<template>
  <div class="radio-group-wrap">
    <slot></slot>
  </div>
</template>
<script>
export default {
  name: 'SkuRadioGroup',
  data () {
    return {
      groupActiveValue: [],
      groupActiveValueId: []
    };
  },
  props: {
    value: {
      type: [String, Object]
    }
  },
  mounted () {
    if (this.value) {
      this.dispatch(this.value, true);
    }
    this.$on('radioChange', this.radioChange);
  },
  methods: {
    dispatch (res, isChange) {
      var radioArr = [];
      if (res.ids.indexOf(';') > -1) {
        radioArr = res.ids.split(';');
        this.groupActiveValue = res.names.split(',');
        this.groupActiveValueId = res.ids.split(';');
      };
      this.$children.map(item => {
        item.isChecked = false;
      });
      radioArr.forEach((item, index) => {
        var id = parseInt(item && item.split(',')[1]);

        var children = this.$children.find(data => id === data.value.id);
        children && children.checkIsActive(id, isChange);
      });
    },
    radioChange (data) {
      var key = data.pid + ',' + data.value.id;
      this.groupActiveValue = this.value.names.split(',');
      this.groupActiveValueId = this.value.ids.split(';');
      // 后台返回的数据是乱的，需要根据类型Id去查对应的KEY
      var indexKey = this.groupActiveValueId.findIndex(item => item.indexOf(data.pid) > -1);
      this.groupActiveValueId.splice(indexKey, 1, key);
      this.groupActiveValue.splice(data.index, 1, data.label);
      var ids = this.groupActiveValueId.join(';');
      var names = this.groupActiveValue.join(',');
      this.groupActiveValueId = this.value.ids.split(';');
      var info = {
        ids: ids,
        names: names
      };
      this.$emit('input', info);
      this.dispatch(info, false);
      this.$emit('change', { ...info, data });
    }
  }
};
</script>
